<template>
  <div class="app-container">
    <el-form :model="baseMessage" :rules="baseMessageFormRules" label-width="100px" ref="baseMessageForm">
      <el-form-item label="课程标题" prop="submitData.title" required>
        <el-input v-model="baseMessage.submitData.title"></el-input>
      </el-form-item>
      <el-form-item label="课程讲师" prop="submitData.teacherId" required>
        <el-select v-model="baseMessage.submitData.teacherId" placeholder="请选择讲师">
          <el-option v-for="teacher in teacherList" :label="teacher.name" :value="teacher.id" :key="teacher.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="课程类别" prop="selectSubject" required>
        <el-cascader
          :options="subjectList"
          v-model="baseMessage.selectSubject"
          clearable
          :props="{value:'id',label:'title'}"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="总课时" prop="submitData.lessonNum" required>
        <el-input-number v-model="baseMessage.submitData.lessonNum" controls-position="right" @change="allCourseTimeChange" :min="1" ></el-input-number>
      </el-form-item>
      <el-form-item label="课程介绍" prop="submitData.description">
        <TinymceEditor v-model="baseMessage.submitData.description"></TinymceEditor>
      </el-form-item>
      <el-form-item label="课程封面" prop="submitData.cover">
        <el-upload
          class="avatar-uploader"
          action="http://127.0.0.1:8002/api/oss/upload-image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :on-error = "imageUploadError"
        >
          <img v-if="baseMessage.submitData.cover" :src="baseMessage.submitData.cover" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="课程价格" prop="submitData.price" required>
        <el-input-number v-model="baseMessage.submitData.price" controls-position="right" @change="allCourseTimeChange" :min="1" ></el-input-number>
      </el-form-item>
    </el-form>
    <div class="bottom-sty">
      <el-button @click="nextStep">下一步</el-button>
    </div>
  </div>
</template>

<script>


  import {simpleTeacherList} from '../../../api/teacher'
  import { loadSubjectList } from '../../../api/subject'

  import TinymceEditor from '../../../components/common/TinymceEditor'

  import * as CourseApi from '../../../api/course'


  export default {
    name: 'CourseBaseMessage',
    components:{
      TinymceEditor
    },
    data: function() {

      return {
        baseMessage:{
          submitData:{
            title: "",
            cover: "",
            description: "",
            lessonNum: 0,
            price: 0,
            subjectId: '',
            subjectParentId: '',
            teacherId: '',
            id: null
          },
          selectSubject:[]
        },
        baseMessageFormRules:{
          "submitData.title":[{ required: true, message: '请输入课程标题', trigger: 'blur' }],
          "submitData.teacherId":[{required:true, message:'请选择教师', trigger: 'blur'}],
          selectSubject:[{type:'array',required:true, message:'请选择课程分类', trigger: 'change'}],
          "submitData.lessonNum":[{required:true,message:'请输入课程时长', trigger: 'blur'}],
          "submitData.cover":[{required:true,message:'请上传课程封面', trigger: 'blur'}],
          "submitData.price":[{required:true,message:'请输入课程价格', trigger: 'blur'}],
        },
        subjectList:[],
        teacherList:[],
        loading: null
      }
    },
    watch:{

      ["baseMessage.selectSubject"](value){

        if (value.length == 2){

          this.baseMessage.submitData.subjectId = value[1];
          this.baseMessage.submitData.subjectParentId = value[0];
        } else {

          this.baseMessage.submitData.subjectId = '';
          this.baseMessage.submitData.subjectParentId = '';
        }

      }
    },
    created: function() {

      this.loadTeacherList();
      this.loadSubjectList();

      if (this.$parent.courseId != null) {

        this.loadCourseBaseMessage();
      }

    },
    methods:{

      nextStep(){


        this.$refs.baseMessageForm.validate((valid) => {

          if (valid) {

            if (this.$parent.courseId != null) {

              this.updateBaseMessage()
            } else {

              this.submitBaseMessage()
            }

          } else {


            return false;
          }

        });


      },
      allCourseTimeChange() {

      },
      async loadTeacherList() {

        this.teacherList = await simpleTeacherList();

      },
      async loadSubjectList() {

        let subjectList = await loadSubjectList(0);

        subjectList.forEach((value)=>{

          value.children.forEach((value)=>{

            delete value.children;
          })
        });

        this.subjectList = subjectList;

      },
      async submitBaseMessage() {

        let response = await CourseApi.submitCourseBaseMessage(this.baseMessage.submitData);

        console.log(response)
        this.$parent.courseId = response.courseId;
        this.$emit('stepAction',1);
      },
      async updateBaseMessage() {

        this.baseMessage.submitData.id = this.$parent.courseId;
        await CourseApi.updateCourseBaseMessage(this.baseMessage.submitData);
        this.$emit('stepAction',1);
      },
      async loadCourseBaseMessage() {

        this.baseMessage.submitData = await  CourseApi.findCourseBaseMessage(this.$parent.courseId);

        this.baseMessage.selectSubject = [this.baseMessage.submitData.subjectParentId,this.baseMessage.submitData.subjectId];
        this.baseMessage.submitData.teacherId =  this.baseMessage.submitData.teacherId + '';
      },
      handleAvatarSuccess(response, file, fileList){

        if (this.loading != null){

          this.loading.close();
          this.loading = null;
        }


        if (response.code != 0){

          this.$message.error("图片上传失败");
        }

        this.baseMessage.submitData.cover = response.data.imageUrl;

      },
      beforeAvatarUpload(){

        this.loading = this.$loading({
          lock: true,
          text: '上传图片中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      },
      imageUploadError(){

        if (this.loading != null){

          this.loading.close();
          this.loading = null;
        }

        this.$message.error("图片上传失败");
      },
    }
  }
</script>

<style>

  .bottom-sty{
    text-align: center;
  }

  .avatar-uploader .el-upload{
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 240px;
    height: 135px;
    line-height: 135px;
    text-align: center;
  }
  .avatar {
    width: 240px;
    height: 135px;
    display: block;
  }

</style>
